from lib.utils.display import Display
import argparse
import sys
import json
from lib.executor.ansible import Playbook

display = Display()


class AdHocCLI(object):
    def __init__(self):
        self.args = self.parse_args()
        
    def parse_args(self):
        """ Command line argument processing """

        parser = argparse.ArgumentParser(description='Auto Gather Main CLI')

        parser.add_argument('-a', '--all-hosts', action='store_true', dest='all_hosts', default=False, help='All Hosts')
        parser.add_argument('-u', '--update-cache', action='store_true', dest='update_cache', default=False, help='Update Cache')
        parser.add_argument('-d', '--display-cache', action='store_true', dest='display_cache', default=False, help='Display Cache')
        parser.add_argument('-e', '--extra-vars', action='store', dest='extra_vars', default=False, 
                             help='set additional variables as JSON')
        parser.add_argument('-r','--refresh-cache', action='store_true', dest='refresh_cache', default=False,
                             help='Force refresh of cache (default: False - use cache files)')
        parser.add_argument('--version', action='version', version='%(prog)s -- 3.2')
        args = parser.parse_args()

        # print "args.all_hosts     -- %s" % args.all_hosts
        # print "args.update_cache  -- %s" % args.update_cache
        # print "args.display_cache -- %s" % args.display_cache
        # print "args.extra_vars    -- %s" % type(eval(args.extra_vars))
        # print "args.refresh_cache -- %s" % args.refresh_cache

        return args

    def run(self):
        if self.args.update_cache:
            self.update()
        else:
            print "Do Nothing!"
            pass

    def update(self):
        if self.args.all_hosts:
            display.info('Auto Gather Started')

            playbook = Playbook()
            playbook.run()

            display.info('Auto Gather Completed')
        elif not self.args.extra_vars:
            print "Error: expected one argument: -e/--extra-vars or -a/--all-hosts"
            print "Show the help message: %s -h" % sys.argv[0] 
        elif self.args.extra_vars:
            display.info('Auto Gather Started')

            playbook = Playbook()
            playbook.run(ip_list=eval(self.args.extra_vars))
            display.info('Auto Gather Completed')
            

def main():
    test_adhoc = AdHocCLI()
    test_adhoc.run()


if __name__ == '__main__':
    main()
